<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;

// 引入模型
use App\Models\Business\Business as BusinessModel;
use App\Models\Ems as EmsModel;
use Illuminate\Support\Facades\DB;
// 消费记录模型
use App\Models\Business\Record as RecordModel;
// 引入Validator 门面 
use Illuminate\Support\Facades\Validator;

use Illuminate\Support\Facades\Mail;

class Business extends Controller
{
    // 注册
    public function register()
    {
        // 获取请求参数，设置默认值为空
        $mobile = request('mobile', '');
        $password = request('password', '');
        $salt = randstr();
        $password = md5($password . $salt);
        $data = [
            'password' => $password,
            'mobile' => $mobile,
            'salt' => $salt,
            'nickname' => $mobile
        ];
        // 验证规则
        $rule = [
            'mobile' => ['required', 'regex:/^1[3456789]{1}\d{9}$/', 'unique:business'],
            'nickname' => ['required'],
            'password' => ['required']

        ];

        // 错误提示信息
        $message = [
            'mobile.required' => '手机号必填',
            'mobile.regex' => '手机号格式错误',
            'mobile.unique' => '手机号已注册',
            'nickname.required' => '密码必填',
            'password.required' => '密码必填',
        ];
        $validator = Validator::make($data, $rule, $message);
        if ($validator->fails()) {
            // 检索特定字段的第一个错误信息 您可以使用 first 方法检索给定字段的第一个错误信息：
            return error($validator->errors()->first());
        }
        $result = BusinessModel::create($data);
        if ($result === false) {
            return error('注册失败');
        } else {
            return success('注册成功');
        }
    }
    // 登陆
    public function login()
    {
        // 获取请求参数，设置默认值为空
        $mobile = request('mobile', '');
        $password = request('password', '');
        $businessinfo = BusinessModel::firstWhere('mobile', $mobile);
        if (!$businessinfo) {
            return error('用户不存在');
        }
        $password = md5($password . $businessinfo['salt']);

        if ($password != $businessinfo['password']) {
            return error('密码错误');
        }
        // 存储用户信息
        $data = [
            'id' => $businessinfo['id'],
            'mobile' => $businessinfo['mobile'],
            'nickname' => $businessinfo['nickname'],
            'avatar' => $businessinfo['avatar_text'],
            'gender' => $businessinfo['gender'],
            'province' => $businessinfo['province'],
            'city' => $businessinfo['city'],
            'district' => $businessinfo['district'],
            'createtime' => $businessinfo['createtime'],
            'money' => $businessinfo['money'],
            'email' => $businessinfo['email'],
            'auth' => $businessinfo['auth'],
        ];

        return success('登陆成功', $data);
    }
    // 校验是否登录
    public function checklogin()
    {
        // 获取请求参数，设置默认值为空
        $mobile = request('mobile', '');
        $id = request('id', '');
        $businessinfo = BusinessModel::firstWhere(['mobile' => $mobile, 'id' => $id]);
        if (!$businessinfo) {
            return error('用户不存在');
        }
        // 存储用户信息
        $data = [
            'id' => $businessinfo['id'],
            'mobile' => $businessinfo['mobile'],
            'nickname' => $businessinfo['nickname'],
            'avatar' => $businessinfo['avatar_text'],
            'gender' => $businessinfo['gender'],
            'province' => $businessinfo['province'],
            'city' => $businessinfo['city'],
            'district' => $businessinfo['district'],
            'createtime' => $businessinfo['createtime'],
            'money' => $businessinfo['money'],
            'email' => $businessinfo['email'],
            'auth' => $businessinfo['auth'],
        ];
        return success('用户存在', $data);
    }
    // 修改用户信息
    public function profile()
    {
        // 获取所有参数
        $params = request()->all();

        $businessinfo = BusinessModel::find($params['id']);

        if (!$businessinfo) {
            return error('用户不存在');
        }
        $data = [
            'nickname' => $params['nickname'],
            'email' => $params['email'],
            'gender' => $params['gender'],
            'province' => $params['province'],
            'city' => $params['city'],
            'district' => $params['district'],
        ];
        // 判断是否修改邮箱
        if ($params['email'] != $businessinfo['email'] && $businessinfo['auth'] == '1') {
            $data['auth'] = '0';
        }
        // 获取图片
        $file = request()->file('avatar');
        if ($file) {
            $res = updload($file);
            if (!$res['code'] == 0) {
                return error($res['msg']);
            }
            $data['avatar'] = $res['data'];
        }

        $password = $params['password'] ?? '';
        // 判断是否修改密码
        if ($password) {

            $salt = randstr();
            // 密码加密
            $password = md5($password . $salt);

            $data['salt'] = $salt;
            $data['password'] = $password;
        }
        $result = BusinessModel::where('id', $params['id'])->update($data);
        if ($result === false) {
            if ($data['avatar']) {
                $b = delete_picture($data['avatar']);
                if (!$b) {
                    return error('更新失败,删除图片失败');
                }
            }
            return error('更新失败');
        } else {
            if ($businessinfo['avatar'] && $file) {
                $b = delete_picture($businessinfo['avatar']);
                if (!$b) {
                    return error('更新成功,删除图片失败');
                }
            }
            return success('更新成功');
        }
    }
    // 发送邮件
    public function sendmail()
    {
        // 获取请求参数，设置默认值为空
        $email = request('email', '');
        $busid = request('busid', 0);
        $businessinfo = BusinessModel::find($busid);
        if (!$businessinfo) {
            return error('用户不存在');
        }
        $emailinfo = EmsModel::firstwhere('email', $email);
        if ($emailinfo) {
            return error('已发送验证码，请去邮箱查收');
        }
        DB::beginTransaction();
        try {
            // 验证码
            $code = randstr(4);
            $data = [
                'event' => '邮箱认证',
                'email' => $email,
                'code' => $code,
            ];
            $EmsStatus = EmsModel::create($data);
            if (!$EmsStatus) {
                return error('发送邮箱验证码失败');
            }
            Mail::raw("验证码：$code", function ($message) use ($email) {
                $message->to($email)->subject('vue商城邮箱认证');
            });
            DB::commit();
            return success('发送成功');
        } catch (\Exception $e) {
            DB::rollBack();
            return error('发送失败');
        }
    }
    // 删除邮箱发送信息
    public function delmail()
    {
        // 获取请求参数，设置默认值为空
        $email = request('email', '');
        $result = EmsModel::where('email', $email)->delete();
        if ($result === false) {
            return error('删除失败');
        } else {
            return success('删除成功');
        }
    }
    // 邮箱认证
    public function email()
    {
        $email = request('email', '');
        $busid = request('busid', 0);
        $code = request('code', '');
        $businessinfo = BusinessModel::find($busid);
        if (!$businessinfo) {
            return error('用户不存在');
        }
        // 查询邮箱校验证表里面
        $emailinfo = EmsModel::where(['email' =>  $email, 'code' => $code])->first();
        if (!$emailinfo) {
            return error('验证码错误，请重新校验');
        }
        // 开启事务
        DB::beginTransaction();
        try {
            BusinessModel::where('id', $busid)->update(['auth' => '1']);
            EmsModel::destroy($emailinfo['id']);
            DB::commit();
            return success('认证成功');
        } catch (\Exception $ex) {
            DB::rollBack();
            return error('认证失败');
        }
    }
    // 忘记密码
    public function forget()
    {
        $mobile = request('mobile', '');
        $businessinfo = BusinessModel::firstWhere('mobile', $mobile);
        if (!$businessinfo) {
            return error('用户不存在');
        }
        if ($businessinfo['auth'] == 0) {
            return error('用户没有邮箱认证');
        }
        return success();
    }
    // 重置密码
    public function reset()
    {
        $mobile = request('mobile', '');
        $code = request('code', '');
        $password = request('password', '');
        $email = request('email', '');
        $businessinfo = BusinessModel::firstWhere(['mobile' => $mobile, 'email' => $email]);
        if (!$businessinfo) {
            return error('不是绑定的邮箱或者用户不存在');
        }
        // 查询邮箱校验证表里面
        $emailinfo = EmsModel::where(['email' =>  $email, 'code' => $code])->first();
        if (!$emailinfo) {
            return error('验证码错误，请重新校验');
        }
        $data = [];
        // 判断是否修改密码
        if ($password) {

            $salt = randstr();
            // 密码加密
            $password = md5($password . $salt);

            $data['salt'] = $salt;
            $data['password'] = $password;
        }
        // 开启事务
        DB::beginTransaction();
        try {
            BusinessModel::where('id', $businessinfo['id'])->update($data);
            EmsModel::destroy($emailinfo['id']);
            DB::commit();
            return success('重置密码成功');
        } catch (\Exception $ex) {
            DB::rollBack();
            return error('重置密码失败');
        }
    }
    // 发送验证码
    public function sendByEmail()
    {
        $email = request('email', '');
        $emailinfo = EmsModel::firstwhere('email', $email);
        if ($emailinfo) {
            return error('已发送验证码，请去邮箱查收');
        }
        DB::beginTransaction();
        try {
            // 验证码
            $code = randstr(4);
            $data = [
                'event' => '密码重置验证',
                'email' => $email,
                'code' => $code,
            ];
            $EmsStatus = EmsModel::create($data);
            if (!$EmsStatus) {
                return error('发送邮箱验证码失败');
            }
            Mail::raw("验证码：$code", function ($message) use ($email) {
                $message->to($email)->subject('vue商城密码重置验证');
            });
            DB::commit();
            return success('发送成功');
        } catch (\Exception $e) {
            DB::rollBack();
            return error('发送失败');
        }
    }
    // 下载图片
    public function updloads()
    {
        $params = request()->all();
        $time = $params['time'];
        $name = $params['name'];
        if (!is_dir("uploads/$time")) {
            mkdir("uploads/$time");
        }
        file_put_contents("uploads/$time/$name", $params['files']);
        return success();
    }
    // 删除图片
    public function delImg()
    {
        $img = (string)request('img', '');
        if (!empty($img)) {
            return is_file(ltrim($img, '/')) && unlink(ltrim($img, '/'));
        }
        return true;
    }
    // 获取消费信息
    public function record()
    {
        $busid = request('busid', 0);
        $num = (int)request('num', 1);
        $businessinfo = BusinessModel::find($busid);
        if (!$businessinfo) {
            return error('用户不存在');
        }
        $count = RecordModel::where('busid', $busid)->count();
        if ($count == 0) {
            return error('暂无消费记录');
        }
        $record = RecordModel::where('busid', $busid)->orderBy('id', 'desc')->paginate(5, ["*"], 'page', $num);
        $data=[];
        if($record){
            $record=$record->toArray();
            $data=$record['data'];
        }
        return success('获取成功', ['record' => $data, 'count' => $count]);
    }
}
